package com.xishu.controller;

import com.xishu.annotation.valid.MethodValidator;
import com.xishu.config.Config;
import com.xishu.entity.foodpanda.Category;
import com.xishu.entity.foodpanda.Product;
import com.xishu.entity.shop.Item;
import com.xishu.entity.shop.PriceConfig;
import com.xishu.foodpanda.FoodPandaConfigService;
import com.xishu.response.ResponseData;
import com.xishu.response.VerifyUtil;
import com.xishu.service.CommonService;
import com.xishu.service.ItemService;
import com.xishu.service.UserService;
import com.xishu.util.ServletUtil;
import com.xishu.util.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import static com.xishu.response.ResponseStatus.PRIVILEGE;
import static com.xishu.response.ResponseStatus.PRODUCT_IMPORTED;

@Api(value = "Product配置")
@RestController
public class ProductController implements Tools {
    private static Logger logger = LoggerFactory.getLogger(ProductController.class);
    private CommonService commonService = CommonService.getInstance();
    private FoodPandaConfigService foodPandaConfigService = FoodPandaConfigService.getInstance();
    private Config config = Config.getInstance();

    @ApiOperation(value = "查询")
    @PutMapping(value = ("/product"), produces = ("application/json;charset=UTF-8"))
    public ResponseData query(@RequestBody Product product) throws Exception {
        return commonService.searchResponse(product);
    }

    @ApiOperation(value = "修改")
    @PutMapping(value = ("/product/modify"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true)
    public ResponseData modify(@RequestBody Product product) throws Exception {
        VerifyUtil.verify(() -> product.getId() != null);
        boolean modifyShowOrder = product.getShowOrder() != null;

        //如果修改了category id，要保证id唯一
        if (product.getCategoryId() != null) {
            Product productInDb = foodPandaConfigService.findProductById(product.getId());
            Product productModifyTarget = foodPandaConfigService.findProduct(product.getCategoryId(), productInDb.getBelongToItemId());
            VerifyUtil.verify(() -> productModifyTarget == null || equals(productModifyTarget.getId(), product.id), PRODUCT_IMPORTED);
        }

        ResponseData responseData = commonService.modifyObject(product);

        if (modifyShowOrder) {
            Product productInDb = foodPandaConfigService.findProductById(product.getId());
            commonService.modifyShowOrder(productInDb, foodPandaConfigService.findProductListByCategoryId(productInDb.getCategoryId()));
        }

        return responseData;
    }

    @ApiOperation(value = "删除")
    @DeleteMapping(value = ("/product"), produces = ("application/json;charset=UTF-8"))
    @MethodValidator(checkShop = true)
    public ResponseData delete(@RequestBody Product product) throws Exception {
        return commonService.delete(product);
    }

    @ApiOperation(value = "从现在的菜里面导入,传菜品列表ids")
    @PostMapping(value = ("/product/import/item/{categoryId}"), produces = ("application/json;charset=UTF-8"))
    public ResponseData importItem(@RequestBody Item item, @PathVariable("categoryId") Long categoryId) throws Exception {
        List<Long> itemIdList = item.ids;

        //如果没有ID，默认为成功
        if (isEmpty(itemIdList)) {
            return ResponseData.emptyResponse();
        }

        VerifyUtil.verify(() -> isNotEmpty(itemIdList));
        Category category = foodPandaConfigService.findCategoryById(categoryId);
        boolean hasShopPrivilege = UserService.getInstance().hasShopPrivilege(ServletUtil.getUser(), category.getShopId());
        VerifyUtil.verify(() -> hasShopPrivilege, PRIVILEGE);

        List<Long> filterImportedItemList = foodPandaConfigService.filterImportedItem(categoryId, itemIdList);

        List<Item> itemList = filterImportedItemList.stream().map(itemId -> {
            try {
                return ItemService.getInstance().findItem(itemId);
            } catch (Exception e) {
                logger.error("e", e);
                return null;
            }
        }).filter(p -> p != null).collect(Collectors.toList());

        itemList = foodPandaConfigService.sortItem(itemList);

        List<Product> productList = itemList.stream().map(item_tmp -> foodPandaConfigService.itemToProduct(item_tmp)).collect(Collectors.toList());
        //依次写品类的名称
        productList.forEach(product -> {
            product.setCategoryName(category.getName());
            product.setCategoryName_zh(category.getName_zh());
            product.setCategoryName_en(category.getName_en());
        });

        List<PriceConfig> priceConfigList = category.getSceneList().stream().map(nameAndId -> {
            PriceConfig priceConfig = new PriceConfig();
            priceConfig.setSceneName(nameAndId.getName());
            priceConfig.setEnable(true);
            priceConfig.setPrice(null);
            priceConfig.setSceneId(nameAndId.getId());
            return priceConfig;
        }).collect(Collectors.toList());

        if (isNotEmpty(productList)) {
            int maxShowOrder = foodPandaConfigService.findMaxShowOrderInCategory(categoryId);
            //依次保存
            for (Product product : productList) {
                maxShowOrder++;
                product.setCategoryId(categoryId);
                //处理价格,所有的价格均处理成空价格
                product.setPriceConfigList(priceConfigList);
                product.setShowOrder(maxShowOrder);
                commonService.createObject(product);
            }
        }

        return ResponseData.emptyResponse();
    }

}

